<template>
	<!-- 今日工时填写 -->
	<view>
		<!-- 固定部分 -->
		<u-sticky bgColor="#fff" :style="{paddingTop:marginTopBot + 'px'}" :customNavHeight="stickyIptTop">
			<realTimeInput @inputDataChangeHandler="inputDataChangeHandler" v-model="iptVal"
				:lastWeekWorkingHours="lastWeekWorkingHours"/>
			<uni-notice-bar style="margin-bottom: 0;text-align: center;" color="#000" background-color="#ffff80" single
				:text="noticeText" />
		</u-sticky>
		<!-- 主体部分 -->
		<!-- 因为底部的按钮占了50px所以要设置padding-bottom,设置margin-bottom无效 -->
		<!-- 因为不知道哪里设置了样式穿透，设置的scoped无效，所以只能用文件名加名称来命名class -->
		<view class="submit_this_week-main-content">
			<!-- 根据状态来判断选择哪个作为插槽内容 -->
			<view v-for="(item,index) in showTotalData.workingHoursDetailedList" :key="index">
				<taskTimeMainContentVue :totalData="showTotalData.workingHoursDetailedList[index]">
					<!-- 展示步进器 -->
					<u-number-box v-if="showStepNumber" decimalLength="1" :min="0" :max="total" :step="0.1"
						v-model="showTotalData.workingHoursDetailedList[index].fillHours" @change="valChange($event.value,item)">
						<h-number-input slot="input" inputAlign="center" border="none" :customStyle="{
								padding: 0,
								height: '30px',
								width: '35px',
								borderRadius: '0',
								backgroundColor: '#EBECEE',
								margin: '0 2px'
								}" defaultNumber="0.0" :min="0" :max="total" v-model="showTotalData.workingHoursDetailedList[index].fillHours"
							@change="valChange($event,item)" placeholderStyle="color: #EBECEE"></h-number-input>
					</u-number-box>
					<!-- 展示文本 -->
					<span v-else>{{showTotalData.workingHoursDetailedList[index].fillHours||0}}</span>
				</taskTimeMainContentVue>
			</view>
		</view>

		<!-- 固定在底部的按钮 -->
		<fixedBottomButtonsVue :showSaveBtn='showSaveBtn' :avoidRepeatSubmitFlag="avoidRepeatSubmitFlag" @clickSubmit="clickSubmit"
			:backPath="backPath">
			<!-- 根据页面状态判断是否显示撤回按钮,后续如果有逻辑改变，可以考虑将相同逻辑的做成computed -->
			<u-button v-if="showRevokeBtn" :disabled="avoidRepeatSubmitFlag" type="primary" text="撤回"
				@click="revokeData"></u-button>
			<u-button v-if="showReturn" type="primary" text="返回" @click="backStep"></u-button>
		</fixedBottomButtonsVue>
	</view>
</template>

<script>
	import realTimeInput from "@/components/real-time-input/realTimeInput"
	import taskTimeMainContentVue from "./components/taskTimeMainContent.vue"
	import fixedBottomButtonsVue from "@/components/fixed-bottom-buttons/fixedBottomButtons.vue"
	// 用来做工时的加减，js原生的不够精确
	// 将数据转成new Decimal(数据),然后用Decimal库的方法做加减或者判断，不能用js原生的方法
	import Decimal from "decimal.js"
	import moment from 'moment'
	import 'moment/locale/zh-cn' // 引入中文语言包
	// 设置语言环境为中文
	moment.locale('zh-cn')
	import {
		getNotFillThisWeekMainData,
		getNotFillThisWeekTaskData,
		getFilledThisWeekMainData,
		getFilledThisWeekTaskData,
		// 本周未撤回，提交本周数据
		addNotFillThisWeekFormData,
		// 撤回本周数据
		revokeThisWeekFormData,
		// 提交撤回过的本周数据
		addRevokeThisWeekFormData,
		generatedFormNumber,
	} from '@/api/taskInput/index.js'

	export default {
		name: 'submitThisWeekTaskTime',
		components: {
			realTimeInput,
			taskTimeMainContentVue,
			fixedBottomButtonsVue
		},
		data() {
			return {
				iptVal: '',
				safeArea: 0,
				stickyIptTop: 44,
				marginTopBot: 10,
				backPath: '/pages/home/home',
				sum: 0,
				// 实际上是常量
				total: 8,
				// 是否展示返回按钮
				showReturn:false,
				// 是否展示提交按钮
				showSaveBtn:true,
				// 是否展示步进器,查看时只展示文字
				showStepNumber: false,
				// 是否展示撤回按钮
				showRevokeBtn: true,
				// 数据状态，是本周未填报的填写，还是填报后的查看，还是撤回后的填写
				status: '',
				// 用户类型，生产统筹人员还是普通员工
				userType: '',
				// 主表数据
				mainData: {},
				// 子表数据，即任务数据，需要根据主表结果以及手动设置查询条件
				taskData: [],
				// 合并主表和子表数据，用于做提交传输给后端
				totalData: {},
				// 内容同totalData，但是用来做前端筛选
				showTotalData: {},
				// 避免重复点击提交按钮
				avoidRepeatSubmitFlag: false,
				lastWeekWorkingHours: [],//以前投入的工时列表
				nowClickParams: {},//当前点击item数据
			}
		},
		computed: {
			// 剩余工时
			remain() {
				return new Decimal(this.total).minus(new Decimal(this.sum))
			},
			noticeText() {
				if (this.status === 'add') {
					return `本日已填工时：${this.sum}(小时)，剩余可填工时：${Math.max(this.remain,0)}(小时)`
				} else {
					return `已填工时：${this.sum}(小时)`
				}
			}
		},
		watch: {
			status: {
				async handler(val) {
					let _mainData
					let _taskData
					// 清空totalData
					this.clearData()
					// 设置初始状态，根据status来判断是否设置fillInTime
					await this.setInitData()
					switch (val) {
						// 本周未填写
						case 'add':
							// 获取主表数据
							_mainData = await getNotFillThisWeekMainData()
							this.mainData = _mainData.result
							_taskData = await getNotFillThisWeekTaskData({
								isInspection: 'no',
								pageNo: 1,
								pageSize: -1
							})
							// 获取子表的数据
							this.taskData = _taskData.result.records
							this.totalData = {
								...this.mainData,
								...this.totalData
							}
							// 合并主表和子表数据，用来传输给后端
							this.totalData.workingHoursDetailedList = this.taskData
							this.showTotalData = JSON.parse(JSON.stringify(this.totalData))
							
							this.lastWeekWorkingHours = [{
								alearyFillButUnStatic: 'no',
								isClick: true,
								nowDate: moment().format('MMMDD日'), //当前日期
								nowWeek: moment().format('dddd') //当前星期
							}]
							this.total = 8
							this.sum = 0
							// 展示步进器
							this.showStepNumber = true
							// 不展示撤回按钮
							this.showRevokeBtn = false
							// 展示保存按钮
							this.showSaveBtn = true
							// 不展示返回按钮
							this.showReturn = false
							break;
							// 今日已填写,查看今日数据
						case 'viewThisDay':
							_mainData = await getFilledThisWeekMainData({ fillInType: 'fill_in' })
							// 得到主表数据，和addNotFilled的数据结构不同
							this.mainData = _mainData.result.records[0]
							// 同上面
							_taskData = await getFilledThisWeekTaskData({ 
								workId: this.mainData.id,
								pageNo: 1,
								pageSize: -1
							})
							this.taskData = _taskData.result.records
							this.totalData = {
								...this.mainData,
								...this.totalData
							}
							this.lastWeekWorkingHours = [{
								alearyFillButUnStatic: 'yes',
								isClick: true,
								nowDate: moment().format('MMMDD日'), //当前日期
								nowWeek: moment().format('dddd') //当前星期
							}]
							this.totalData.workingHoursDetailedList = this.taskData
							this.showTotalData = JSON.parse(JSON.stringify(this.totalData))
							this.calculateSum()
							// this.noticeText = `本周已填工时：${this.sum}(小时)`
							// 不展示步进器，只展示数据
							this.showStepNumber = false
							// 展示撤回按钮需要判断，如果是在定时任务跑批期间，以及已统计的数据，都是不能撤回的
							if(this.totalData.statisticalStatus!='no'){
								this.showRevokeBtn = false
								this.showSaveBtn = false
								this.showReturn = true
							}else{								
							// 展示撤回按钮
							this.showRevokeBtn = true
							this.showSaveBtn = false
							this.showReturn = false
							}
							break;

							// 撤回重填，接口大体类似查看
						case 'revokeAdd':
							_mainData = await getFilledThisWeekMainData({ fillInType: 'fill_in' })
							// 得到主表数据，和addNotFilled的数据结构不同
							this.mainData = _mainData.result.records[0]
							// 同上面
							_taskData = await getFilledThisWeekTaskData({
								workId: this.mainData.id,
								pageNo: 1,
								pageSize: -1
							})
							this.taskData = _taskData.result.records
							this.totalData = {
								...this.mainData,
								...this.totalData
							}
							this.totalData.workingHoursDetailedList = this.taskData
							this.showTotalData = JSON.parse(JSON.stringify(this.totalData))
							this.calculateSum()
							// 不展示步进器，只展示数据
							this.showStepNumber = true
							// 展示撤回按钮
							this.showRevokeBtn = false
						default:
							break;
					}
				}
			}
		},
		onLoad(obj) {
			this.status = obj.iptStatus
			this.userType = obj.userType
		},
		created() {
			uni.getSystemInfo({
				success(e) {
					uni.setStorageSync('getSystemInfo', e);
				}
			})
			this.safeArea = uni.getStorageSync('getSystemInfo').safeArea.top
			this.stickyIptTop = this.safeArea + 44
			// #ifdef APP-PLUS
			this.stickyIptTop = 0
			// #endif
		},
		methods: {

			// 设置fillInTime
			async setInitData() {
				if (this.status === 'add') {
					// 获取单据编号
					const _res = await generatedFormNumber({type: 'fill_in'})
					_res && this.$set(this.totalData, 'billNo', _res)
				}
				if (this.status === 'add' || this.status === 'revokeAdd') {
					this.$set(this.totalData, 'fillInTime', moment().format('YYYY-MM-DD HH:mm:ss'))
				}
			},
			// 返回上一级目录
			backStep() {
				uni.reLaunch({
					url: this.backPath
				})
			},
			// 计算总数
			calculateSum() {
				this.sum = new Decimal(0)
				for (let item of this.totalData.workingHoursDetailedList) {
					this.sum = this.sum.add(new Decimal(item.fillHours || 0))
				}
			},
			// 触发步进器数据更新
			valChange(e, item) {
				// 这里的更新会慢，所以用下面这个，获取到更新后的再去做计算
				this.$nextTick(() => {
					let _tItem = this.totalData.workingHoursDetailedList.find(tItem => {
						return tItem.projectTaskId === item.projectTaskId
					})
					_tItem.fillHours = e
					let comArr = [...this.totalData.workingHoursDetailedList, ...this.showTotalData.workingHoursDetailedList]
					this.totalData.workingHoursDetailedList = this.$utils.uniqueByKey(comArr, 'projectTaskId')
					this.calculateSum()
				})
			},

			// 点击子组件触发，计算是否符合提交的标准
			async clickSubmit() {
				this.calculateSum()
				let _res = null
				// 禁止重复点击提交
				this.avoidRepeatSubmitFlag = true
				if (this.judgeCanSubmit()) {
					if (this.status === 'revokeAdd') {
						this.$set(this.totalData, 'fillInStatus', 'yes')
						_res = await addRevokeThisWeekFormData(this.totalData)
						// 如果提交失败，则停止操作
						if (!_res.success) {

							this.avoidRepeatSubmitFlag = false

							return
						}
					} else if (this.status === 'add') {
						_res = await addNotFillThisWeekFormData(this.totalData)
						// 如果提交失败，则停止操作
						if (!_res.success) {

							this.avoidRepeatSubmitFlag = false

							return
						}
					}
					// 提交成功的共同操作
					if (_res.success) {
						this.$utils.uniDlgCallBack({
							title: '提示',
							showCancel: false,
							content: '工时填报提交成功',
							success: ()=>{
								this.avoidRepeatSubmitFlag = false
								this.backStep()
							}
						})
					}
				} else {
					// 判断不可提交后，也应该重置提交按钮可点击
					this.avoidRepeatSubmitFlag = false
				}
			},
			// 判断是否可以提交
			judgeCanSubmit() {
				const _sum = new Decimal(this.sum)
				const _total = new Decimal(this.total)
				if (_sum.equals(_total)) {
					return true
				} else if (_sum.lessThan(_total)) {
					if (this.userType === 'coordinator') {
						this.$utils.toast(`当前工时之和必须等于${this.total}小时才可提交`)
						return false
					}
					if(this.userType === 'product_coordinator' || this.userType === 'r_and_d_coordinator'){
						/* 生产/研发统筹人员，工时可小于或等于8小时 */
						return true
					}
					this.$utils.toast(`当前工时之和小于${this.total}小时，不可提交`)
					return false
				} else {
					this.$utils.toast(`当前工时之和大于${this.total}小时，不可提交`)
					return false
				}
			},
			// 监听输入框事件
			async inputDataChangeHandler(value) {
				this.iptVal = value
				// 前端过滤
				this.showTotalData.workingHoursDetailedList = this.totalData.workingHoursDetailedList.filter(item => {
					return item.projectName.indexOf(this.iptVal) != -1
				})
			},
			// 撤回按钮
			async revokeData() {
				this.$utils.uniDlgCallBack({
					title: '提示',
					content: '是否撤回？',
					success: async (res)=>{
						let params = {
							id: this.mainData.id,
							// fillInStatus: 'cancel',
						}
						this.avoidRepeatSubmitFlag = true
						const _res = await revokeThisWeekFormData(params)
						if (_res.success) {
							this.$utils.toast('撤回工时填报成功')
							this.status = 'add'
							// this.sum = 0
							// this.total = 8
						} else {
							this.$utils.toast(_res.message || '操作失败！')
						}
						this.avoidRepeatSubmitFlag = false
					}
				})
			},
			// 清空数据
			clearData(){
				this.totalData = this.$options.data().totalData
			}
		}
	}
</script>

<style lang="scss" scoped>
	.task-time-submit {
		position: fixed;
		top: 0;
		left: 0;
		background-color: rgb(30, 111, 255);
		color: rgb(255, 255, 255);
		padding: 7px 6px;
		width: 100%;
		z-index: 998;
		display: flex;
		justify-content: space-between;
		box-sizing: border-box;

		.uni-page-head__title {
			font-size: 16px;
			font-weight: 700;
			line-height: 30px;
			text-align: center;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
			max-width: 260px;
		}
	}

	.submit_this_week-main-content {
		background: #f2f2f2;
		padding-bottom: 50px;
	}
</style>